package org.example.service.error;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * @Author: tang
 * @Description:
 * @Date 2025/5/15 09:34
 */
@Slf4j
@Component
public class ErrorReceiver {

    @RabbitListener(queues = {"ex.tang.error"})
    public void handler(String msg, @Headers Map<String, Object> headers, Channel channel) {
        System.out.println("收到的消息---》" + msg);
        Long deliveryTag  = (Long)headers.get(AmqpHeaders.DELIVERY_TAG);
        try {
            // 模拟异常
            if ("hello world!".equals(msg)) {
                throw new RuntimeException("自定义异常:消息消费失败!");
            }
            // 手动确认
            channel.basicAck(deliveryTag,false);
        } catch (Exception e) {
            log.error("消息消费失败，deliveryTag：{}", deliveryTag);
            try {
                // 是否重新入队？取决于你的业务需求 推荐 false
                // 推荐设置为 false，避免无限循环
                boolean requeue = false;
                channel.basicNack(deliveryTag, false, requeue);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        }
    }

    @RabbitListener(queues = {"ex.tang.error.1"},errorHandler = "testRabbitListenerErrorHandler")
    public void test01Handler(String msg, @Headers Map<String, Object> headers, Channel channel) {
        Long deliveryTag  = (Long)headers.get(AmqpHeaders.DELIVERY_TAG);
        try {
            // 模拟异常
            if ("hello world!".equals(msg)) {
                throw new RuntimeException("自定义异常:消息消费失败!");
            }
            // 手动确认
            channel.basicAck(deliveryTag,false);
        } catch (Exception e) {
            log.error("消息消费失败，deliveryTag：{}", deliveryTag);
            try {
                // 是否重新入队？取决于你的业务需求 推荐 false
                // 推荐设置为 false，避免无限循环
                boolean requeue = false;
                channel.basicNack(deliveryTag, false, requeue);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
            throw new SomeSpecificException(e);
        }
    }
}
